#include "mainwindow.h"
#include <QApplication>
#include <QTextCodec>
#include <QDesktopWidget>
#include <QTranslator>
#include <QLocale>
#include <qlockfile.h>
#include "xatom-helper.h"
#include <QSystemSemaphore>
#include <QSharedMemory>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    QString LaunchMode = "";
    if(argc > 2)
    {
        qDebug()<<"传入错误参数错误";
        return 0;
    }
    else
    {
        if(argc == 1)
        {
            LaunchMode = "MANUAL";
        }
        else
        {
            QString Mode = "";
            Mode = argv[1];
            if(Mode == "-s")
            {
                LaunchMode = "SILENCE";
                qDebug()<<"静默安装";
            }
            else if(Mode == "-m")
            {
                LaunchMode = "MANUAL";
                qDebug()<<"手动启动";
            }
            else
            {
                qDebug()<<"传入参数错误";
                return 0;
            }
        }

    }
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QApplication a(argc, argv);

    QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    //需要给文件锁加一个DISPLAY标识
    int fd = open(QString(homePath.at(0) + "/.config/kylin-update-desktop%1.lock").arg(getenv("DISPLAY")).toUtf8().data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd < 0) { exit(1); }
    if (lockf(fd, F_TLOCK, 0)) {
        qDebug() << "Can't lock single file, kylin-update-desktop is already running!";
        exit(0);
    }

    QDesktopWidget *desktop = QApplication::desktop();
    int width = desktop->width();
    int height = desktop->height();

    QTranslator translator;
    QString locale = QLocale::system().name();
    if(locale == "zh_CN") {
        translator.load(":/qmfile/translation/update_zh_CN.qm");
    }
    a.installTranslator(&translator);

    a.setApplicationName(QObject::tr("kylin-system-upgrade"));
    a.setWindowIcon(QIcon::fromTheme("kylin-update-desktop"));

    MainWindow w(LaunchMode);
    w.move((width - w.width()) / 2, (height - w.height()) / 2);
    // 添加窗管协议
    MotifWmHints hints;
    hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
    hints.functions = MWM_FUNC_ALL;
    hints.decorations = MWM_DECOR_BORDER;
    XAtomHelper::getInstance()->setWindowMotifHint(w.winId(), hints);
    w.show();

    return a.exec();
}
